package com.sgam.mf.web;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import com.sgam.mf.domain.entity.ApplicationProjectType;
import com.sgam.mf.domain.entity.ApplicationPropertyType;
import com.sgam.mf.domain.entity.ClientFiles;
import com.sgam.mf.domain.entity.ContractAsig;
import com.sgam.mf.domain.entity.Contracts;
import com.sgam.mf.domain.entity.RegCompanies;
import com.sgam.mf.domain.entity.RegCompaniesShort;
import com.sgam.mf.domain.entity.RegPartners;
import com.sgam.mf.domain.entity.RegPersons;
import com.sgam.mf.domain.ref.RefActivityType;
import com.sgam.mf.domain.ref.RefAssCompany;
import com.sgam.mf.domain.ref.RefAssType;
import com.sgam.mf.domain.ref.RefBank;
import com.sgam.mf.domain.ref.RefBranch;
import com.sgam.mf.domain.ref.RefCityHall;
import com.sgam.mf.domain.ref.RefCompany;
import com.sgam.mf.domain.ref.RefCurrency;
import com.sgam.mf.domain.ref.RefDomains;
import com.sgam.mf.domain.ref.RefLivePlace;
import com.sgam.mf.domain.ref.RefObjectAss;
import com.sgam.mf.domain.ref.RefPersonType;
import com.sgam.mf.domain.ref.RefProjectType;
import com.sgam.mf.domain.ref.RefPropertyType;
import com.sgam.mf.domain.ref.RefRegion;
import com.sgam.mf.domain.ref.RefRole;
import com.sgam.mf.domain.ref.RefServices;
import com.sgam.mf.domain.ref.RefStatus;
import com.sgam.mf.domain.sec.SecUser;
import com.sgam.mf.domain.sys.SysMainMenu;
import com.sgam.mf.helper.ProxyCurrentUser;
import com.sgam.mf.service.entity.ContractsService;
import com.sgam.mf.service.entity.RegCompaniesService;
import com.sgam.mf.service.entity.RegCompaniesShortService;
import com.sgam.mf.service.entity.RegPartnersService;
import com.sgam.mf.service.entity.RegPersonsService;
import com.sgam.mf.service.ref.RefActivityTypeService;
import com.sgam.mf.service.ref.RefAssCompanyService;
import com.sgam.mf.service.ref.RefAssTypeService;
import com.sgam.mf.service.ref.RefBankService;
import com.sgam.mf.service.ref.RefBranchService;
import com.sgam.mf.service.ref.RefCityHallService;
import com.sgam.mf.service.ref.RefCompanyService;
import com.sgam.mf.service.ref.RefCurrencyService;
import com.sgam.mf.service.ref.RefDomainsService;
import com.sgam.mf.service.ref.RefLivePlaceService;
import com.sgam.mf.service.ref.RefObjectAssService;
import com.sgam.mf.service.ref.RefPersonTypeService;
import com.sgam.mf.service.ref.RefProjectTypeService;
import com.sgam.mf.service.ref.RefPropertyTypeService;
import com.sgam.mf.service.ref.RefRegionService;
import com.sgam.mf.service.ref.RefRoleService;
import com.sgam.mf.service.ref.RefServicesService;
import com.sgam.mf.service.ref.RefStatusService;
import com.sgam.mf.service.sec.SecUserService;
import com.sgam.mf.service.sys.SysMainMenuService;

@Controller
public class AppController {
		
	protected final Logger log = Logger.getLogger(getClass());
	
	/* ******************************   REFERENCIES              ****************************** */	
	@Autowired private RefRoleService 					refRoleService;
	@Autowired private RefCompanyService 				refCompanyService;
	@Autowired private RefBankService 					refBankService;
	@Autowired private RefActivityTypeService			refActivityTypeService;	
	@Autowired private RefDomainsService				refDomainsService;
	@Autowired private RefServicesService				refServicesService;
	@Autowired private RefStatusService					refStatusService;
	@Autowired private RefPersonTypeService				refPersonTypeService;
	@Autowired private RefLivePlaceService				refLivePlaceService;
	@Autowired private RefPropertyTypeService 			refPropertyTypeService;
	@Autowired private RefBranchService 				refBranchService;
	@Autowired private RefRegionService					refRegionService;
	@Autowired private RefCityHallService				refCityHallService;
	@Autowired private RefProjectTypeService			refProjectTypeService;
	@Autowired private RefAssTypeService				refAssTypeService;	
	@Autowired private RefCurrencyService				refCurrencyService;
	@Autowired private RefObjectAssService				refObjectAssService;
	@Autowired private RefAssCompanyService				refAssCompanyService;

	/* ******************************   REGISTRY	              ****************************** */	
	@Autowired private RegPersonsService 				regPersonsService;
	@Autowired private RegCompaniesService 				regCompaniesService;
	@Autowired private RegCompaniesShortService 		regCompaniesShortService;
	@Autowired private RegPartnersService				regPartnersService;

	/* ******************************   ENTITY		              ****************************** */	
	@Autowired private ContractsService 				contractsService;
	
	/* ******************************   SECURITY	              ****************************** */
	@Autowired private SecUserService 					secUserService;

	
	/* ******************************   SYSTEM		              ****************************** */
	@Autowired private SysMainMenuService				sysMainMenuService;	
	
	

	/* ******************************   MISCELLANIOUS ROUTINES  ****************************** */
   @ModelAttribute("currentUserName")
  	public String currentUser() {
	   Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	   log.debug("Authentication auth  = " + auth.getName());
    	//SecUser item = secUserService.getCurrentSecUser();
    	return auth.getName(); 
  	}
   
   
   @ModelAttribute("proxyCurrentUser")
 	public ProxyCurrentUser proxyCurrentUser() {
	   
	   ProxyCurrentUser item = secUserService.getProxyCurrentUser();
   	//SecUser item = secUserService.getCurrentSecUser();
   	return item; 
 	}
   
   
   
   @ModelAttribute("mainMenu")
  	public String mainMenu() {
	   Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	   List<SysMainMenu>		preResult = sysMainMenuService.listTree();
	   String result = printSysMenuItems(preResult );
	   return result; 
  	}
	
   private String printSysMenuItems(List<SysMainMenu> entityList) {
	   String  resMenu = "";
	   List<SysMainMenu> tmpList = entityList;
	   Collections.sort(tmpList);
     	for (SysMainMenu temp : tmpList) {
     		resMenu += temp.toHTMLStringOpen();
	   		if (temp.getItems().size() > 0) {
	   			resMenu  = resMenu + "<ul>";
	   			resMenu = resMenu + printSysMenuItems(temp.getItems()); 
	   			resMenu  = resMenu + "</ul>";
	   		}
	   		resMenu = resMenu +  temp.toHTMLStringClose();
     	}
     	return resMenu;
   }
   
  // @ModelAttribute("regCompaniesCBX")
  	public List<RegCompaniesShort> regCompaniesCBX() {
	   log.debug("AppController - regCompaniesCBX");
    	//SecUser item = secUserService.getCurrentSecUser();
    	return regCompaniesShortService.list(secUserService.getProxyCurrentUser()); 
  	} 
  	
  	public List<RegPartners> regPartnersCBX() {
  	   log.debug("AppController - regPartnersCBX");
      	//SecUser item = secUserService.getCurrentSecUser();
      	return regPartnersService.list(secUserService.getProxyCurrentUser()); 
    	} 
   
  // @ModelAttribute("refCompanyCBX")
  	public List<RefCompany> refCompanyCBX() {
	   log.debug("AppController - regCompaniesCBX");
    	return refCompanyService.list(secUserService.getProxyCurrentUser()); 
  	} 
   
   //@ModelAttribute("refActivityTypeCBX")
  	public List<RefActivityType> refActivityTypeCBX() {
	   log.debug("AppController - refActivityTypeCBX");
    	return refActivityTypeService.list(secUserService.getProxyCurrentUser()); 
  	}    
   
   //@ModelAttribute("refBankCBX")
  	public List<RefBank> refBankCBX() {
	   log.debug("AppController - refBankCBX");
    	return refBankService.list(secUserService.getProxyCurrentUser()); 
  	}   
  	
    //@ModelAttribute("refCurrencyCBX")
   	public List<RefCurrency> refCurrencyCBX() {
 	   log.debug("AppController - refCurrencyCBX");
     	return refCurrencyService.list(secUserService.getProxyCurrentUser()); 
   	} 
   
   //@ModelAttribute("refDomainsCBX")
  	public List<RefDomains> refDomainsCBX() {
	   log.debug("AppController - refDomainsCBX");
    	return refDomainsService.list(secUserService.getProxyCurrentUser()); 
  	}  
   
   //@ModelAttribute("refServicesCBX")
  	public List<RefServices> refServicesCBX() {
	   log.debug("AppController - refServicesCBX");
    	return refServicesService.list(secUserService.getProxyCurrentUser()); 
  	} 
   
   //@ModelAttribute("refStatusCBX")
  	public List<RefStatus> refStatusCBX() {
	   log.debug("AppController - refStatusCBX");
    	return refStatusService.list(secUserService.getProxyCurrentUser()); 
  	} 
   
   //@ModelAttribute("refPersonTypeCBX")
  	public List<RefPersonType> refPersonTypeCBX() {
	   log.debug("AppController - refPersonTypeCBX");
    	return refPersonTypeService.list(secUserService.getProxyCurrentUser()); 
  	} 
   
   //@ModelAttribute("refLivePlaceCBX")
  	public List<RefLivePlace> refLivePlaceCBX() {
	   log.debug("AppController - refLivePlaceCBX");
    	return refLivePlaceService.list(secUserService.getProxyCurrentUser()); 
  	} 
   
   //@ModelAttribute("refPropertyTypeCBX")
  	public List<RefPropertyType> refPropertyTypeCBX() {
	   log.debug("AppController - refPropertyTypeCBX");
    	return refPropertyTypeService.list(secUserService.getProxyCurrentUser()); 
  	}
   
   //@ModelAttribute("refBranchCBX")
 	public List<RefBranch> refBranchCBX() {
	   log.debug("AppController - refBranchCBX");
   	return refBranchService.list(secUserService.getProxyCurrentUser()); 
 	} 
 	
    //@ModelAttribute("refObjectAssCBX")
  	public List<RefObjectAss> refObjectAssCBX() {
 	   log.debug("AppController - refObjectAssCBX");
    	return refObjectAssService.list(secUserService.getProxyCurrentUser()); 
  	} 
  	
    //@ModelAttribute("refAssCompanyCBX")
  	public List<RefAssCompany> refAssCompanyCBX() {
 	   log.debug("AppController - refAssCompanyCBX");
    	return refAssCompanyService.list(secUserService.getProxyCurrentUser()); 
  	} 
   
   //@ModelAttribute("refRoleCBX")
  	public List<RefRole> refRoleCBX() {
	   log.debug("AppController - refRoleCBX");
    	return refRoleService.list(secUserService.getProxyCurrentUser()); 
  	}    
   
   //@ModelAttribute("secUserCBX")
  	public List<SecUser> secUserCBX() {
	   log.debug("AppController - secUserCBX");
    	return secUserService.list(secUserService.getProxyCurrentUser()); 
  	} 
   
  
   public List<RefRegion>  refRegionsCBX () {
   	log.debug("AppController - refRegionsCBX ");
   	List<RefRegion> result = refRegionService.list(secUserService.getProxyCurrentUser());
   	Collections.sort(result);
       return  result;
   }      
   
 
   public List<RefCityHall>  refCityHallsCBX () {
   	log.debug("AppController - refCityHallsCBX ");
   	List<RefCityHall> result = refCityHallService.list(secUserService.getProxyCurrentUser());
   	Collections.sort(result);
    return  result;
   }  
      
   //@ModelAttribute("refAssTypeCBX")
	public List<RefAssType> refAssTypeCBX() {
	   log.debug("AppController - refAssTypeCBX");
  	return refAssTypeService.list(secUserService.getProxyCurrentUser()); 
	} 
   
   /* ******************************   GLOBAL ROUTINES      ****************************** */  
   
    @RequestMapping("/")
    public String bar(WebRequest request, Principal principal, Locale locale) {
    	System.out.println("AppController - / redirection to ");
        return "redirect:/home";
    }    
            
    @RequestMapping("/index") 
    public String index(Map<String, Object> map, WebRequest request, Principal principal) {
    	System.out.println("AppController - index ");
    	return "redirect:/public";
    } 
    
    @RequestMapping("/login") 
    public String login(Map<String, Object> map, WebRequest request, Principal principal) {
    	System.out.println("AppController - login ");
    	return "public";
    }    
    
    @RequestMapping("/public") 
    public String publicPage(ModelMap model) {
    	System.out.println("AppController - public ");
    	return "public";
    }    
    
    
    @RequestMapping("/loginfailed") 
    public String loginfailed(ModelMap model) {
    	System.out.println("AppController - loginfailed ");
    	model.addAttribute("error", "true");
    	return "public";
    }
    
    @RequestMapping("/home")
    public String home(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - home");
        return "home";
    }    
    

    
/* **********************************************************************************
 *		ADAUGA
 * ********************************************************************************** */    
    
    @RequestMapping("/adauga")
    public String adauga(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - utilitati");
        return "adauga";
    }    
    
    @RequestMapping("/adaugaClient")
    public String adaugaClient(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - adaugaClient");
        return "adauga";
    }    
    

    
    /* ----------------------- PERSON SPECIFIC ------------------------------------ */
    
    @RequestMapping(value="/adaugaClientiPersoana", method=RequestMethod.GET) 
    public String  adaugaClientiPersoanaGet(Model m , @RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaClientiPersoanaGet - GET");
    	RegPersons personsItem = null;
    	try {
    		if (pId != null) {
    			personsItem = regPersonsService.get(pId, secUserService.getProxyCurrentUser());
        	} else {
        		personsItem = new RegPersons();
        	}
        	
    		if (personsItem != null) {
    			m.addAttribute("personsItem", personsItem);
    		} else {
    			m.addAttribute("personsItem", new RegPersons());
    		}
        		
    		m.addAttribute("errorMessage", "0");
		} catch (Exception e) {
			m.addAttribute("personsItem", new RegPersons());
			m.addAttribute("errorMessage", "Server Side Error Occured");
		}
    	
    	m.addAttribute("regCompaniesCBX", regCompaniesCBX());
    	m.addAttribute("refAssTypeCBX", 	refAssTypeCBX());
    	
    	return "personsCard";
    }
    
    @RequestMapping(value="/adaugaClientiPersoana", method=RequestMethod.POST) 
    public String  adaugaClientiPersoanaPost( Model m , @ModelAttribute("personsItem") RegPersons item,  
    													@RequestParam(value="pPostOperation", required=false) String pPostOperation) {
    	log.debug("AppController - adaugaClientiPersoanaPost - POST");
    	log.debug("AppController - adaugaClientiPersoanaPost - pPostOperation = " +  pPostOperation );
    	RegPersons personsItem = null;
    	RegCompanies companiesItem = null;
//    	try {
    		log.debug("Size:"+item.getRegPersonsAss().size());
        	item.setUpdatedByFk(secUserService.getCurrentUserId());
        	item.setUpdatedDate(new Date());
        	if(item.getRegCompanies().getId() == null || item.getRegCompanies().getId() == -1) {
        		item.setRegCompanies(null);
        	}
        	//working with files start----------------------------------------------------------------------------
        	int needCopyFilesFlg=0;
        	if(item.getId()!= null) {
        		item.setClientFiles((regPersonsService.get(item.getId(), secUserService.getProxyCurrentUser())).getClientFiles());
        		if (item.getRegCompanies() != null && item.getId()!=null) {
        			log.debug("Company id from Persons New:"+item.getRegCompanies().getId());
        			
        			personsItem = regPersonsService.get(item.getId(), secUserService.getProxyCurrentUser());
        			
        			if (personsItem.getRegCompanies()!= null) {
	        			log.debug("Company id from Persons old(DB):"+personsItem.getRegCompanies().getId());
	        			
	        			if (item.getRegCompanies().getId() != personsItem.getRegCompanies().getId()) {  	
	        				log.debug("Companys id not much!");
	        				needCopyFilesFlg=1;
	        			}
        			}
        			else {
        				log.debug("Companys id change from null!");
        				needCopyFilesFlg=1;
        			}
        		}
        	}
        	if (needCopyFilesFlg==1) {
    			companiesItem = regCompaniesService.get(item.getRegCompanies().getId(), secUserService.getProxyCurrentUser());
    			
        		List <ClientFiles> cList = item.getClientFiles(); //PF Files
        		List <ClientFiles> cListT = new ArrayList <ClientFiles>();
        		
        		if (companiesItem.getClientFiles()!=null) {
        			for (int i = 0; i < companiesItem.getClientFiles().size(); i++) {
        				cListT.add(companiesItem.getClientFiles().get(i));
        			}
        		}
        		
        		for (int i = 0; i < cList.size(); i++) {
        			ClientFiles cFile = new ClientFiles();
        			cFile.setdBStoredFile(cList.get(i).getdBStoredFile());
        			cFile.setRefDomains(cList.get(i).getRefDomains());
        			//cFile.setId(null);
	        		cListT.add(cFile);

        		}	    

    			companiesItem.setClientFiles(cListT);
    			log.debug("Companys files for id "+companiesItem.getId()+" count="+companiesItem.getClientFiles().size());
    			regCompaniesService.update(companiesItem, secUserService.getProxyCurrentUser());
    			log.debug("Companys files were updated!");
        	}
        	//working with files stop----------------------------------------------------------------------------
        	personsItem = regPersonsService.update(item, secUserService.getProxyCurrentUser());
//		} catch (Exception e) {
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	
      	if (pPostOperation.equalsIgnoreCase("remain")) {
    		m.addAttribute("personsItem", personsItem);
    		
    		m.addAttribute("regCompaniesCBX", 	regCompaniesCBX());
    		m.addAttribute("refAssTypeCBX", 	refAssTypeCBX());
    		
    		m.addAttribute("errorMessage", "0");
    		return "personsCard"; 
    	} 
      m.asMap().clear();
      return "redirect:/vizualizeazaClientiPersoana";
    }    
    
    /* ----------------------- COMPANIES SPECIFIC ------------------------------------ */
    
    @RequestMapping(value="/adaugaClientCompanie", method=RequestMethod.GET) 
    public String  adaugaClientCompanieGet(Model m , @RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaClientCompanieGet - GET");
    	RegCompanies companiesItem = null;
//    	RegCompaniesAss regCompaniesAssItem=null;
//    	List<RegCompaniesAss> regCompaniesAssList;
//    	try {
    		if (pId != null) {
    			companiesItem = regCompaniesService.get(pId, secUserService.getProxyCurrentUser());
        	} 
    		else {
    			companiesItem=new RegCompanies();
//    			regCompaniesAssItem=new RegCompaniesAss();
//    			regCompaniesAssList=new ArrayList<RegCompaniesAss>();
//    			regCompaniesAssList.add(regCompaniesAssItem);
//    			
//    			companiesItem.setRegCompaniesAss(regCompaniesAssList);
    		}
    		
    		if (companiesItem != null) {
    			m.addAttribute("companiesItem", companiesItem);
    		} else {
    			m.addAttribute("companiesItem", new RegCompanies());
    		}
        		
    		m.addAttribute("errorMessage", "0");
//		} catch (Exception e) {
//			m.addAttribute("companiesItem", new RegCompanies());
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	
    	m.addAttribute("refActivityTypeCBX", refActivityTypeCBX());
    	m.addAttribute("refBankCBX",		 refBankCBX());
    	m.addAttribute("refAssTypeCBX",		 refAssTypeCBX());
    	
    	return "companiesCard";
    }
    
	@RequestMapping(value = "/adaugaClientCompanie", method = RequestMethod.POST)
	public String adaugaClientCompaniePost(
			Model m,
			@ModelAttribute("companiesItem") RegCompanies item,
			@RequestParam(value = "pPostOperation", required = false) String pPostOperation) {
		
		log.debug("AppController - adaugaClientCompaniePost - POST");
		log.debug("AppController - adaugaClientCompaniePost - pPostOperation = "
				+ pPostOperation);
		RegCompanies companiesItem = null;
		
		try {
			if(item.getRefActivityType().getId() == null || item.getRefActivityType().getId() == -1) {
        		item.setRefActivityType(null);
        	}
			
			if(item.getRefBank().getId() == null || item.getRefBank().getId() == -1) {
        		item.setRefBank(null);
        	}
			
			
			item.setUpdatedByFk(secUserService.getCurrentUserId());
			item.setUpdatedDate(new Date());
			
			if(item.getId()!= null) {
        		item.setClientFiles((regCompaniesService.get(item.getId(), secUserService.getProxyCurrentUser())).getClientFiles());
        	}
			
			companiesItem = regCompaniesService.update(item, secUserService.getProxyCurrentUser());
		} catch (Exception e) {
			m.addAttribute("errorMessage", "Server Side Error Occured");
		}

		if (pPostOperation.equalsIgnoreCase("remain")) {
			m.addAttribute("companiesItem", companiesItem);
			
			m.addAttribute("refActivityTypeCBX", refActivityTypeCBX());
	    	m.addAttribute("refBankCBX",		 refBankCBX());
	    	m.addAttribute("refAssTypeCBX",		 refAssTypeCBX());
	    	
			m.addAttribute("errorMessage", "0");
			return "companiesCard";
		}
		m.asMap().clear();
		return "redirect:/vizualizeazaClientiCompanie";
	}

    /* ----------------------- PARTENERI SPECIFIC ------------------------------------ */
    
    @RequestMapping(value="/adaugaParteneri", method=RequestMethod.GET) 
    public String  adaugaParteneriGet(Model m , @RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaParteneriGet - GET");
    	RegPartners parteneriItem = null;
//    	RegCompaniesAss regCompaniesAssItem=null;
//    	List<RegCompaniesAss> regCompaniesAssList;
//    	try {
    		if (pId != null) {
    			parteneriItem = regPartnersService.get(pId, secUserService.getProxyCurrentUser());
        	} 
    		else {
    			parteneriItem=new RegPartners();
//    			
//    			companiesItem.setRegCompaniesAss(regCompaniesAssList);
    		}
    		
    		if (parteneriItem != null) {
    			m.addAttribute("parteneriItem", parteneriItem);
    		} else {
    			m.addAttribute("parteneriItem", new RegPartners());
    		}
        		
    		m.addAttribute("errorMessage", "0");
    		
    		m.addAttribute("refAssTypeCBX", 	refAssTypeCBX());
//		} catch (Exception e) {
//			m.addAttribute("companiesItem", new RegCompanies());
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	return "parteneriCard";
    }
    
	@RequestMapping(value = "/adaugaParteneri", method = RequestMethod.POST)
	public String adaugaParteneriPost(
			Model m,
			@ModelAttribute("parteneriItem") RegPartners item,
			@RequestParam(value = "pPostOperation", required = false) String pPostOperation) {
		
		log.debug("AppController - adaugaParteneriPost - POST");
		log.debug("AppController - adaugaParteneriPost - pPostOperation = "
				+ pPostOperation);
		RegPartners parteneriItem = null;
		
		try {
			
			//item.setUpdatedByFk(secUserService.getCurrentUserId());
			//item.setUpdatedDate(new Date());
			parteneriItem = regPartnersService.update(item, secUserService.getProxyCurrentUser());
		} catch (Exception e) {
			m.addAttribute("errorMessage", "Server Side Error Occured");
		}

		if (pPostOperation.equalsIgnoreCase("remain")) {
			m.addAttribute("parteneriItem", parteneriItem);
			m.addAttribute("refAssTypeCBX", 	refAssTypeCBX());
	    	
			m.addAttribute("errorMessage", "0");
			return "parteneriCard";
		}
		
		m.asMap().clear();
		return "redirect:/vizualizeazaParteneri";
	}  
	
	
   /* ----------------------- SEC USERS - UTILIZATORI ------------------------------------ */
    
    @RequestMapping(value="/adaugaPersonal", method=RequestMethod.GET) 
    public String  adaugaPersoanalGet(Model m , @RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaPersoanalGet - GET");
    	SecUser personalItem = null;
    	try {
    		if (pId != null) {
    			personalItem = secUserService.get(pId, secUserService.getProxyCurrentUser());
        	} 
        	
    		if (personalItem != null) {
    			m.addAttribute("personalItem", personalItem);
    		} else {
    			m.addAttribute("personalItem", secUserService.getNewUser());
    		}
        		
    		m.addAttribute("errorMessage", "0");
		} catch (Exception e) {
			m.addAttribute("personalItem", secUserService.getNewUser());
			m.addAttribute("errorMessage", "Server Side Error Occured");
		}
    	
    	 m.addAttribute("refRegionsCBX", 	refRegionsCBX());
    	 m.addAttribute("refCityHallsCBX", 	refCityHallsCBX());
    	 m.addAttribute("refBranchCBX", 	refBranchCBX());
    	 m.addAttribute("refRoleCBX", 		refRoleCBX());
    	 
    	return "usersCard";
    }
	
	
    @RequestMapping(value="/adaugaPersonal", method=RequestMethod.POST) 
    public String  adaugaPersoanalPersoanaPost( Model m , @ModelAttribute("personalItem") SecUser item,  
    													@RequestParam(value="pPostOperation", required=false) String pPostOperation) {
    	log.debug("AppController - adaugaPersoanalPersoanaPost - POST");
    	log.debug("AppController - adaugaPersoanalPersoanaPost - pPostOperation = " +  pPostOperation );
    	SecUser personalItem = null;
    	//try {

    		item.setUpdatedByFk(secUserService.getCurrentUserId());
        	item.setUpdatedDate(new Date());
        	personalItem = secUserService.update(item, secUserService.getProxyCurrentUser());

        	
        	//} catch (Exception e) {
//			m.addAttribute("errorMessage", "Server Side Error Occured");
		//}
    	
    	//m.asMap().clear();
 	 	
      	if (pPostOperation.equalsIgnoreCase("remain")) {
    		m.addAttribute("personalItem", personalItem);
    		
        	m.addAttribute("refRegionsCBX", 	refRegionsCBX());
     	 	m.addAttribute("refCityHallsCBX", 	refCityHallsCBX());
     	 	m.addAttribute("refBranchCBX", 		refBranchCBX());
     	 	m.addAttribute("refRoleCBX", 		refRoleCBX());
     	 	
    		
    		m.addAttribute("errorMessage", "0");
    		return "usersCard"; 
    	} 
      	
      return "redirect:/vizualizeazaPersonal";
    }    
    
    
    /* ============================================================================================ */    
    
    @RequestMapping(value="/clientiPFListPopup", method = {RequestMethod.GET, RequestMethod.POST}) 
    public String  usersListPopup( Model m, @RequestParam(value="returnEntity") String returnEntity ) {
    	log.debug("AppController - clientiPFListPopup - GET,POST");
    	m.addAttribute("returnEntity", returnEntity);
    	return "clientiPFListPopup";
    }  
    
    @RequestMapping(value="/clientiPFCardPopup", method = {RequestMethod.GET}) 
    public String  clientiPFCardPopupGET( Model m, 	@RequestParam(value="returnEntity") String returnEntity,  
    												@RequestParam(value="pfId", required=false ,defaultValue="-1") 		Integer pfId) {
    	log.debug("AppController - clientiPFCardPopup - GET");
    	log.debug("AppController - pfId = " + pfId);
    	m.addAttribute("returnEntity", returnEntity);
    	
    	if (pfId>0) {
    		m.addAttribute("personsItem", regPersonsService.get(pfId, secUserService.getProxyCurrentUser()));
    	} else {
    		m.addAttribute("personsItem", new RegPersons());	
    	}
    	
    	m.addAttribute("regCompaniesCBX", 	regCompaniesCBX());
    	m.addAttribute("refAssTypeCBX", 	refAssTypeCBX());
    	
    	return "clientiPFCardPopup";
    }  
    
    @RequestMapping(value="/clientiPFCardPopup", method = {RequestMethod.POST}) 
    public @ResponseBody RegPersons  clientiPFCardPopupPOST( Model m,  @ModelAttribute("personsItem") RegPersons item ) {
    	
    	log.debug("AppController - clientiPFCardPopup - POST");
    	
    	RegPersons personsItemResult = new RegPersons();
    	RegCompanies companiesItem = new RegCompanies();
    	RegPersons personsItem = new RegPersons();
    	try {
        	item.setUpdatedByFk(secUserService.getCurrentUserId());
        	item.setUpdatedDate(new Date());
        	if(item.getRegCompanies().getId() == null || item.getRegCompanies().getId() == -1) {
        		item.setRegCompanies(null);
        	}
        	
        	//working with files start----------------------------------------------------------------------------
        	int needCopyFilesFlg=0;
        	if(item.getId()!= null) {
        		item.setClientFiles((regPersonsService.get(item.getId(), secUserService.getProxyCurrentUser())).getClientFiles());
        		if (item.getRegCompanies() != null && item.getId()!=null) {
        			log.debug("Company id from Persons New:"+item.getRegCompanies().getId());
        			
        			personsItem = regPersonsService.get(item.getId(), secUserService.getProxyCurrentUser());
        			
        			if (personsItem.getRegCompanies()!= null) {
	        			log.debug("Company id from Persons old(DB):"+personsItem.getRegCompanies().getId());
	        			
	        			if (item.getRegCompanies().getId() != personsItem.getRegCompanies().getId()) {  	
	        				log.debug("Companys id not much!");
	        				needCopyFilesFlg=1;
	        			}
        			}
        			else {
        				log.debug("Companys id change from null!");
        				needCopyFilesFlg=1;
        			}
        		}
        	}
        	if (needCopyFilesFlg==1) {
    			companiesItem = regCompaniesService.get(item.getRegCompanies().getId(), secUserService.getProxyCurrentUser());
    			
        		List <ClientFiles> cList = item.getClientFiles(); //PF Files
        		List <ClientFiles> cListT = new ArrayList <ClientFiles>();
        		
        		if (companiesItem.getClientFiles()!=null) {
        			for (int i = 0; i < companiesItem.getClientFiles().size(); i++) {
        				cListT.add(companiesItem.getClientFiles().get(i));
        			}
        		}
        		
        		for (int i = 0; i < cList.size(); i++) {
        			ClientFiles cFile = new ClientFiles();
        			cFile.setdBStoredFile(cList.get(i).getdBStoredFile());
        			cFile.setRefDomains(cList.get(i).getRefDomains());
        			//cFile.setId(null);
	        		cListT.add(cFile);

        		}	    

    			companiesItem.setClientFiles(cListT);
    			log.debug("Companys files for id "+companiesItem.getId()+" count="+companiesItem.getClientFiles().size());
    			regCompaniesService.update(companiesItem, secUserService.getProxyCurrentUser());
    			log.debug("Companys files were updated!");
        	}
        	//working with files stop----------------------------------------------------------------------------
        	
        	personsItemResult = regPersonsService.update(item, secUserService.getProxyCurrentUser());
		} catch (Exception e) {
			m.addAttribute("errorMessage", "Server Side Error Occured");
			e.printStackTrace();
		}
    	
    	return personsItemResult;
    }  
    
    
    /* ============================================================================================ */
    
    @RequestMapping(value="/clientiPJListPopup", method = {RequestMethod.GET, RequestMethod.POST}) 
    public String  clientiPJListPopup( Model m, @RequestParam(value="returnEntity") String returnEntity ) {
    	log.debug("AppController - clientiPJListPopup - GET,POST");
    	m.addAttribute("returnEntity", returnEntity);
    	return "clientiPJListPopup";
    } 
    
    @RequestMapping(value="/clientiPJCardPopup", method = {RequestMethod.GET}) 
    public String  clientiPJCardPopupGET( Model m, @RequestParam(value="returnEntity") String returnEntity,  
													@RequestParam(value="pjId", required=false ,defaultValue="-1") 		Integer pjId ) {
    	log.debug("AppController - clientiPJCardPopup - GET");
    	log.debug("AppController - pjId = " + pjId);
    	m.addAttribute("returnEntity", returnEntity);
    	
    	if (pjId>0) {
    		m.addAttribute("companiesItem", regCompaniesShortService.get(pjId, secUserService.getProxyCurrentUser()));
    	} else {
    		m.addAttribute("companiesItem", new RegCompanies()); 	
    	}
    	
    	
    	m.addAttribute("refActivityTypeCBX", 	refActivityTypeCBX());
    	m.addAttribute("refBankCBX",		 	refBankCBX());
    	m.addAttribute("refAssTypeCBX", 	refAssTypeCBX());
    	
    	return "clientiPJCardPopup";
    }  
    
    @RequestMapping(value="/clientiPJCardPopup", method = { RequestMethod.POST}) 
    public @ResponseBody RegCompanies  clientiPJCardPopupPOST( Model m,  @ModelAttribute("companiesItem") RegCompanies item ) {
    	log.debug("AppController - clientiPJCardPopup - POST");
    	
    	RegCompanies companiesItemResult = new RegCompanies();
    	try {
    		if(item.getRefActivityType().getId() == null || item.getRefActivityType().getId() == -1) {
        		item.setRefActivityType(null);
        	}
			
			if(item.getRefBank().getId() == null || item.getRefBank().getId() == -1) {
        		item.setRefBank(null);
        	}
			
        	item.setUpdatedByFk(secUserService.getCurrentUserId());
        	item.setUpdatedDate(new Date());
        	
        	companiesItemResult = regCompaniesService.update(item, secUserService.getProxyCurrentUser());
		} catch (Exception e) {
			m.addAttribute("errorMessage", "Server Side Error Occured");
			e.printStackTrace();
		}
    	
    	return companiesItemResult;
    }  
    /* ============================================================================================ */    
    
    /* ----------------------- REF BANK - PARTENERI ------------------------------------ */    
    
    @RequestMapping(value="/adaugaPartener", method=RequestMethod.GET) 
    public String  adaugaPartenerGet(Model m , @RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaPartenerGet - GET");
    	RefBank partenerItem = null;
    	try {
    		if (pId != null) {
    			partenerItem = refBankService.get(pId, secUserService.getProxyCurrentUser());
        	} 
        	
    		if (partenerItem != null) {
    			m.addAttribute("partenerItem", partenerItem);
    		} else {
    			m.addAttribute("partenerItem", new RefBank());
    		}
        		
    		m.addAttribute("errorMessage", "0");
		} catch (Exception e) {
			m.addAttribute("partenerItem", new RefBank());
			m.addAttribute("errorMessage", "Server Side Error Occured");
		}
    	return "partenerCard";
    }
	
	
    @RequestMapping(value="/adaugaPartener", method=RequestMethod.POST) 
    public String  adaugaPartenerPost( Model m , @ModelAttribute("personalItem") 		RefBank item,  
    											 @RequestParam(value="pPostOperation", required=false) String pPostOperation) {
    	log.debug("AppController - adaugaPartenerPost - POST");
    	log.debug("AppController - adaugaPartenerPost - pPostOperation = " +  pPostOperation );
    	RefBank partenerItem = null;
    	try {
        	item.setUpdatedBy(secUserService.getCurrentUserId());
        	item.setUpdatedDate(new Date());
        	partenerItem = refBankService.update(item, secUserService.getProxyCurrentUser());
		} catch (Exception e) {
			m.addAttribute("errorMessage", "Server Side Error Occured");
		}
    	
      	if (pPostOperation.equalsIgnoreCase("remain")) {
    		m.addAttribute("partenerItem", partenerItem);	
    		m.addAttribute("errorMessage", "0");
    		return "partenerCard"; 
    	} 
      m.asMap().clear();
      return "redirect:/vizualizeazaPartener";
    }    
    
    
    
/* **********************************************************************************
 *		VIZUALIZEAZA
 * ********************************************************************************** */     
    @RequestMapping("/vizualizeaza")
    public String vizualizeaza(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeaza");
        return "vizualizeaza";
    }    
    
    @RequestMapping("/vizualizeazaClient")
    public String vizualizeazaClienti(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - adaugaClient");
        return "vizualizeaza";
    }  
    
    /* ----------------------- PERSON SPECIFIC ------------------------------------ */    

    

    @RequestMapping("/vizualizeazaClientiPersoana")
    public String vizualizeazaClientiPersoana(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaClientiPersoana");
        return "personsList";
    } 
    
    /* ----------------------- COMPANIES SPECIFIC ------------------------------------ */    
    
    @RequestMapping("/vizualizeazaClientiCompanie")
    public String vizualizeazaClientiCompanie(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaClientiCompanie");
        return "companiesList";
    } 
    
   /* ----------------------- PARTENERI SPECIFIC ------------------------------------ */    

    @RequestMapping("/vizualizeazaParteneri")
    public String vizualizeazaParteneri(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaClientiPersoana");
        return "parteneriList";
    } 
    
    /* ----------------------- PERSONAL SPECIFIC ------------------------------------ */
    
    @RequestMapping("/vizualizeazaPersonal")
    public String vizualizeazaPersonal(Model m , WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaPersonal");
     	m.addAttribute("refRegionsCBX", refRegionsCBX());
 	 	m.addAttribute("refCityHallsCBX", refCityHallsCBX());
        return "usersList";
    }     

    
    /* -----------------------  REF BANK PARTENER SPECIFIC ------------------------------------ */
    
    @RequestMapping("/vizualizeazaPartener")
    public String vizualizeazaPartener(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaPartener");
        return "partenerList";
    }     
    
    /* ----------------------- CONTRACT SPECIFIC ------------------------------------ */
    
    @RequestMapping("/vizualizeazaContracte")
    public String vizualizeazaContracte(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaContracte");
        return "contractsList";
    }  
    
    @RequestMapping("/vizualizeazaAnchete")
    public String vizualizeazaAnchete(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaAnchete");
        return "applicationsList";
    }  
    
    @RequestMapping(value="/adaugaContract", method=RequestMethod.GET) 
    public String  adaugaContractGet(Model m , @RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaContractGet - GET");
     	return "contractsCard";
    }
    
    @RequestMapping(value="/adaugaContractFinBank", method=RequestMethod.GET) 
    public String  adaugaContractFinBankGet(Model m ,HttpServletRequest request, 
    		@RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaContractFinBankGet - GET");
    	
    	
    	Contracts contractItem = new Contracts();
//    	List<RefActivityType> refActivityType=null;
    	List<RefPropertyType> refPropertyType=null;
//    	try {
    		if (pId != null) {
    			contractItem = contractsService.get(pId, secUserService.getProxyCurrentUser());
    			if (contractItem.getRefStatus().getId()==2 && contractItem.getContractDate()==null){
    				contractItem.setContractDate(new Date());
    			}
        	} 
    		else {
//    		refActivityType = refActivityTypeService.list(secUserService.getProxyCurrentUser());
//			ApplicationActivityType applicationActivityType; 
//			List<ApplicationActivityType> appList=new ArrayList<ApplicationActivityType>();
			
			refPropertyType = refPropertyTypeService.list(secUserService.getProxyCurrentUser());
			
			ApplicationPropertyType applicationPropertyType; 
			List<ApplicationPropertyType> appList1=new ArrayList<ApplicationPropertyType>();
			
			
//			for (int i = 0; i < refActivityType.size(); i++) {
//				applicationActivityType=new ApplicationActivityType();
//				applicationActivityType.setRefActivityType(refActivityType.get(i));
//				appList.add(applicationActivityType);
//			}
			
			for (int i = 0; i < refPropertyType.size(); i++) {
				applicationPropertyType=new ApplicationPropertyType();
				applicationPropertyType.setRefPropertyType(refPropertyType.get(i));
				appList1.add(applicationPropertyType);
			}
			//log.debug("Dom2="+request.getParameter("pDomain"));
			if (Integer.parseInt(request.getParameter("pDomain"))==1) {
				ApplicationProjectType applicationProjectType; 
				List<ApplicationProjectType> appProj = new ArrayList<ApplicationProjectType>();
				List<RefProjectType> refProjectType=null;//new ArrayList<RefProjectType>();
				//log.debug("Serv="+request.getParameter("pService"));
				refProjectType=refProjectTypeService.listByService(Integer.parseInt(request.getParameter("pService")));
				for (int i = 0; i < refProjectType.size(); i++) {
					applicationProjectType=new ApplicationProjectType();
					applicationProjectType.setRefProjectType(refProjectType.get(i));
					appProj.add(applicationProjectType);
					//log.debug(applicationProjectType.getRefProjectType().getMdValue());
				}
				contractItem.setApplicationProjectType(appProj);
			}
			
			
//			contractItem.setApplicationActivityType(appList);
			contractItem.setApplicationPropertyType(appList1);
			contractItem.setAppRegDate(new Date());

			contractItem.setRefStatus(new RefStatus());
			contractItem.getRefStatus().setId(0);
    		}
    		
    		if (contractItem != null) {
    			m.addAttribute("contractItem", contractItem);
    		} else {
    			m.addAttribute("contractItem", new Contracts());
    		}
        		
    		m.addAttribute("errorMessage", "0");
//		} catch (Exception e) {
//			log.debug(e.toString());
//			m.addAttribute("contractItem", new Contracts());
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	
    	m.addAttribute("refCompanyCBX", 		refCompanyCBX());
    	m.addAttribute("refActivityTypeCBX", 	refActivityTypeCBX());
    	m.addAttribute("refDomainsCBX", 		refDomainsCBX());
    	m.addAttribute("refServicesCBX", 		refServicesCBX());
    	m.addAttribute("refStatusCBX", 			refStatusCBX());
    	m.addAttribute("refPersonTypeCBX", 		refPersonTypeCBX());
    	m.addAttribute("refLivePlaceCBX", 		refLivePlaceCBX());
    	m.addAttribute("refPropertyTypeCBX", 	refPropertyTypeCBX());
    	m.addAttribute("refBranchCBX", 			refBranchCBX());
    	m.addAttribute("secUserCBX", 			secUserCBX());
    	m.addAttribute("refBankCBX",		 	refBankCBX());
    	m.addAttribute("regPartnersCBX",		regPartnersCBX());
    	
     	return "contractsCardFinBank";
    }

    
    @RequestMapping(value="/adaugaContractMM", method=RequestMethod.GET) 
    public String  adaugaContractMMGet(Model m ,HttpServletRequest request, 
    		@RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaContractMMGet - GET");
    	
    	
    	Contracts contractItem = new Contracts();
//    	List<RefActivityType> refActivityType=null;
    	List<RefPropertyType> refPropertyType=null;
//    	try {
    		if (pId != null) {
    			contractItem = contractsService.get(pId, secUserService.getProxyCurrentUser());
    			if (contractItem.getRefStatus().getId()==2 && contractItem.getContractDate()==null){
    				contractItem.setContractDate(new Date());
    			}
        	} 
    		else {
//    		refActivityType = refActivityTypeService.list(secUserService.getProxyCurrentUser());
//			ApplicationActivityType applicationActivityType; 
//			List<ApplicationActivityType> appList=new ArrayList<ApplicationActivityType>();
			
			refPropertyType = refPropertyTypeService.list(secUserService.getProxyCurrentUser());
			
			ApplicationPropertyType applicationPropertyType; 
			List<ApplicationPropertyType> appList1=new ArrayList<ApplicationPropertyType>();
			
			
//			for (int i = 0; i < refActivityType.size(); i++) {
//				applicationActivityType=new ApplicationActivityType();
//				applicationActivityType.setRefActivityType(refActivityType.get(i));
//				appList.add(applicationActivityType);
//			}
			
			for (int i = 0; i < refPropertyType.size(); i++) {
				applicationPropertyType=new ApplicationPropertyType();
				applicationPropertyType.setRefPropertyType(refPropertyType.get(i));
				appList1.add(applicationPropertyType);
			}
			//log.debug("Dom2="+request.getParameter("pDomain"));
			if (Integer.parseInt(request.getParameter("pDomain"))==1) {
				ApplicationProjectType applicationProjectType; 
				List<ApplicationProjectType> appProj = new ArrayList<ApplicationProjectType>();
				List<RefProjectType> refProjectType=null;//new ArrayList<RefProjectType>();
				//log.debug("Serv="+request.getParameter("pService"));
				refProjectType=refProjectTypeService.listByService(Integer.parseInt(request.getParameter("pService")));
				for (int i = 0; i < refProjectType.size(); i++) {
					applicationProjectType=new ApplicationProjectType();
					applicationProjectType.setRefProjectType(refProjectType.get(i));
					appProj.add(applicationProjectType);
					//log.debug(applicationProjectType.getRefProjectType().getMdValue());
				}
				contractItem.setApplicationProjectType(appProj);
			}
			
			
//			contractItem.setApplicationActivityType(appList);
			contractItem.setApplicationPropertyType(appList1);
			contractItem.setAppRegDate(new Date());

			contractItem.setRefStatus(new RefStatus());
			contractItem.getRefStatus().setId(0);
    		}
    		
    		if (contractItem != null) {
    			m.addAttribute("contractItem", contractItem);
    		} else {
    			m.addAttribute("contractItem", new Contracts());
    		}
        		
    		m.addAttribute("errorMessage", "0");
//		} catch (Exception e) {
//			log.debug(e.toString());
//			m.addAttribute("contractItem", new Contracts());
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	
    	m.addAttribute("refCompanyCBX", 		refCompanyCBX());
    	m.addAttribute("refActivityTypeCBX", 	refActivityTypeCBX());
    	m.addAttribute("refDomainsCBX", 		refDomainsCBX());
    	m.addAttribute("refServicesCBX", 		refServicesCBX());
    	m.addAttribute("refStatusCBX", 			refStatusCBX());
    	m.addAttribute("refPersonTypeCBX", 		refPersonTypeCBX());
    	m.addAttribute("refLivePlaceCBX", 		refLivePlaceCBX());
    	m.addAttribute("refPropertyTypeCBX", 	refPropertyTypeCBX());
    	m.addAttribute("refBranchCBX", 			refBranchCBX());
    	m.addAttribute("secUserCBX", 			secUserCBX());
    	m.addAttribute("refBankCBX",		 	refBankCBX());
    	m.addAttribute("refCurrencyCBX",	 	refCurrencyCBX());
    	
     	return "contractsCardMM";
    }
    
    
    @RequestMapping(value="/adaugaContractImob", method=RequestMethod.GET) 
    public String  adaugaContractImobGet(Model m ,HttpServletRequest request, 
    		@RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaContractImobGet - GET");
    	
    	
    	Contracts contractItem = new Contracts();
//    	List<RefActivityType> refActivityType=null;
    	//List<RefPropertyType> refPropertyType=null;
//    	try {
    		if (pId != null) {
    			contractItem = contractsService.get(pId, secUserService.getProxyCurrentUser());
    			if ( contractItem.getContractDate()==null){//contractItem.getRefStatus().getId()==1 &&
    				contractItem.setContractDate(new Date());
    			}
        	} 
    		else {
//    		refActivityType = refActivityTypeService.list(secUserService.getProxyCurrentUser());
//			ApplicationActivityType applicationActivityType; 
//			List<ApplicationActivityType> appList=new ArrayList<ApplicationActivityType>();
			
//			refPropertyType = refPropertyTypeService.list(secUserService.getProxyCurrentUser());
//			
//			ApplicationPropertyType applicationPropertyType; 
//			List<ApplicationPropertyType> appList1=new ArrayList<ApplicationPropertyType>();
			
			
//			for (int i = 0; i < refActivityType.size(); i++) {
//				applicationActivityType=new ApplicationActivityType();
//				applicationActivityType.setRefActivityType(refActivityType.get(i));
//				appList.add(applicationActivityType);
//			}
			
//			for (int i = 0; i < refPropertyType.size(); i++) {
//				applicationPropertyType=new ApplicationPropertyType();
//				applicationPropertyType.setRefPropertyType(refPropertyType.get(i));
//				appList1.add(applicationPropertyType);
//			}
			//log.debug("Dom2="+request.getParameter("pDomain"));
			if (Integer.parseInt(request.getParameter("pDomain"))==1) {
				ApplicationProjectType applicationProjectType; 
				List<ApplicationProjectType> appProj = new ArrayList<ApplicationProjectType>();
				List<RefProjectType> refProjectType=null;//new ArrayList<RefProjectType>();
				//log.debug("Serv="+request.getParameter("pService"));
				refProjectType=refProjectTypeService.listByService(Integer.parseInt(request.getParameter("pService")));
				for (int i = 0; i < refProjectType.size(); i++) {
					applicationProjectType=new ApplicationProjectType();
					applicationProjectType.setRefProjectType(refProjectType.get(i));
					appProj.add(applicationProjectType);
					//log.debug(applicationProjectType.getRefProjectType().getMdValue());
				}
				contractItem.setApplicationProjectType(appProj);
			}
			
			
//			contractItem.setApplicationActivityType(appList);
//			contractItem.setApplicationPropertyType(appList1);
			contractItem.setAppRegDate(new Date());

			contractItem.setRefStatus(new RefStatus());
			contractItem.getRefStatus().setId(0);
    		}
    		
    		if (contractItem != null) {
    			m.addAttribute("contractItem", contractItem);
    		} else {
    			m.addAttribute("contractItem", new Contracts());
    		}
        		
    		m.addAttribute("errorMessage", "0");
//		} catch (Exception e) {
//			log.debug(e.toString());
//			m.addAttribute("contractItem", new Contracts());
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	
    	m.addAttribute("refCompanyCBX", 		refCompanyCBX());
    	m.addAttribute("refActivityTypeCBX", 	refActivityTypeCBX());
    	m.addAttribute("refDomainsCBX", 		refDomainsCBX());
    	m.addAttribute("refServicesCBX", 		refServicesCBX());
    	m.addAttribute("refStatusCBX", 			refStatusCBX());
    	m.addAttribute("refPersonTypeCBX", 		refPersonTypeCBX());
    	m.addAttribute("refLivePlaceCBX", 		refLivePlaceCBX());
    	m.addAttribute("refPropertyTypeCBX", 	refPropertyTypeCBX());
    	m.addAttribute("refBranchCBX", 			refBranchCBX());
    	m.addAttribute("secUserCBX", 			secUserCBX());
    	m.addAttribute("refBankCBX",		 	refBankCBX());
    	//m.addAttribute("refCurrencyCBX",	 	refCurrencyCBX());
    	
     	return "contractsCardImob";
    }
    
    @RequestMapping(value="/adaugaContractEvCont", method=RequestMethod.GET) 
    public String  adaugaContractEvContGet(Model m ,HttpServletRequest request, 
    		@RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaContractEvContGet - GET");
    	
    	
    	Contracts contractItem = new Contracts();
//    	List<RefActivityType> refActivityType=null;
    	//List<RefPropertyType> refPropertyType=null;
//    	try {
    		if (pId != null) {
    			contractItem = contractsService.get(pId, secUserService.getProxyCurrentUser());
    			if ( contractItem.getContractDate()==null){//contractItem.getRefStatus().getId()==1 &&
    				contractItem.setContractDate(new Date());
    			}
        	} 
    		else {
//    		refActivityType = refActivityTypeService.list(secUserService.getProxyCurrentUser());
//			ApplicationActivityType applicationActivityType; 
//			List<ApplicationActivityType> appList=new ArrayList<ApplicationActivityType>();
			
//			refPropertyType = refPropertyTypeService.list(secUserService.getProxyCurrentUser());
//			
//			ApplicationPropertyType applicationPropertyType; 
//			List<ApplicationPropertyType> appList1=new ArrayList<ApplicationPropertyType>();
			
			
//			for (int i = 0; i < refActivityType.size(); i++) {
//				applicationActivityType=new ApplicationActivityType();
//				applicationActivityType.setRefActivityType(refActivityType.get(i));
//				appList.add(applicationActivityType);
//			}
			
//			for (int i = 0; i < refPropertyType.size(); i++) {
//				applicationPropertyType=new ApplicationPropertyType();
//				applicationPropertyType.setRefPropertyType(refPropertyType.get(i));
//				appList1.add(applicationPropertyType);
//			}
			//log.debug("Dom2="+request.getParameter("pDomain"));
			if (Integer.parseInt(request.getParameter("pDomain"))==1) {
				ApplicationProjectType applicationProjectType; 
				List<ApplicationProjectType> appProj = new ArrayList<ApplicationProjectType>();
				List<RefProjectType> refProjectType=null;//new ArrayList<RefProjectType>();
				//log.debug("Serv="+request.getParameter("pService"));
				refProjectType=refProjectTypeService.listByService(Integer.parseInt(request.getParameter("pService")));
				for (int i = 0; i < refProjectType.size(); i++) {
					applicationProjectType=new ApplicationProjectType();
					applicationProjectType.setRefProjectType(refProjectType.get(i));
					appProj.add(applicationProjectType);
					//log.debug(applicationProjectType.getRefProjectType().getMdValue());
				}
				contractItem.setApplicationProjectType(appProj);
			}
			
			
//			contractItem.setApplicationActivityType(appList);
//			contractItem.setApplicationPropertyType(appList1);
			contractItem.setAppRegDate(new Date());

			contractItem.setRefStatus(new RefStatus());
			contractItem.getRefStatus().setId(0);
    		}
    		
    		if (contractItem != null) {
    			m.addAttribute("contractItem", contractItem);
    		} else {
    			m.addAttribute("contractItem", new Contracts());
    		}
        		
    		m.addAttribute("errorMessage", "0");
//		} catch (Exception e) {
//			log.debug(e.toString());
//			m.addAttribute("contractItem", new Contracts());
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	
    	m.addAttribute("refCompanyCBX", 		refCompanyCBX());
    	m.addAttribute("refActivityTypeCBX", 	refActivityTypeCBX());
    	m.addAttribute("refDomainsCBX", 		refDomainsCBX());
    	m.addAttribute("refServicesCBX", 		refServicesCBX());
    	m.addAttribute("refStatusCBX", 			refStatusCBX());
    	m.addAttribute("refPersonTypeCBX", 		refPersonTypeCBX());
    	m.addAttribute("refLivePlaceCBX", 		refLivePlaceCBX());
    	m.addAttribute("refPropertyTypeCBX", 	refPropertyTypeCBX());
    	m.addAttribute("refBranchCBX", 			refBranchCBX());
    	m.addAttribute("secUserCBX", 			secUserCBX());
    	m.addAttribute("refBankCBX",		 	refBankCBX());
    	//m.addAttribute("refCurrencyCBX",	 	refCurrencyCBX());
    	
     	return "contractsCardEvCont";
    }
    
    @RequestMapping(value="/adaugaContractAsig", method=RequestMethod.GET) 
    public String  adaugaContractAsigGet(Model m ,HttpServletRequest request, 
    		@RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaContractAsigGet - GET");
    	
    	
    	Contracts contractItem = new Contracts();
//    	List<RefActivityType> refActivityType=null;
    	//List<RefPropertyType> refPropertyType=null;
//    	try {
    		if (pId != null) {
    			contractItem = contractsService.get(pId, secUserService.getProxyCurrentUser());
    			if ( contractItem.getContractDate()==null){//contractItem.getRefStatus().getId()==1 &&
    				contractItem.setContractDate(new Date());
    			}
        	} 
    		else {
//    		refActivityType = refActivityTypeService.list(secUserService.getProxyCurrentUser());
//			ApplicationActivityType applicationActivityType; 
//			List<ApplicationActivityType> appList=new ArrayList<ApplicationActivityType>();
			
//			refPropertyType = refPropertyTypeService.list(secUserService.getProxyCurrentUser());
//			
//			ApplicationPropertyType applicationPropertyType; 
//			List<ApplicationPropertyType> appList1=new ArrayList<ApplicationPropertyType>();
			
			
//			for (int i = 0; i < refActivityType.size(); i++) {
//				applicationActivityType=new ApplicationActivityType();
//				applicationActivityType.setRefActivityType(refActivityType.get(i));
//				appList.add(applicationActivityType);
//			}
			
//			for (int i = 0; i < refPropertyType.size(); i++) {
//				applicationPropertyType=new ApplicationPropertyType();
//				applicationPropertyType.setRefPropertyType(refPropertyType.get(i));
//				appList1.add(applicationPropertyType);
//			}
			//log.debug("Dom2="+request.getParameter("pDomain"));
		
			
//			contractItem.setApplicationActivityType(appList);
//			contractItem.setApplicationPropertyType(appList1);
    		contractItem.setContractAsig(new ContractAsig());
    		contractItem.getContractAsig().setDateFrom(new Date());
    		
    		Calendar cal = Calendar.getInstance();
    		//Date today = cal.getTime();
    		cal.add(Calendar.YEAR, 1); // to get previous year add -1
    		cal.add(Calendar.DATE, -1);
    		Date nextYear = cal.getTime();
    		contractItem.getContractAsig().setDateTo(nextYear);
    		contractItem.setPrepayment(0);
    		
			contractItem.setAppRegDate(new Date());

			contractItem.setRefStatus(new RefStatus());
			contractItem.getRefStatus().setId(4);
    		}
    		
    		if (contractItem != null) {
    			m.addAttribute("contractItem", contractItem);
    		} else {
    			m.addAttribute("contractItem", new Contracts());
    		}
        		
    		m.addAttribute("errorMessage", "0");
//		} catch (Exception e) {
//			log.debug(e.toString());
//			m.addAttribute("contractItem", new Contracts());
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	
    	m.addAttribute("refCompanyCBX", 		refCompanyCBX());
    	m.addAttribute("refActivityTypeCBX", 	refActivityTypeCBX());
    	m.addAttribute("refDomainsCBX", 		refDomainsCBX());
    	m.addAttribute("refServicesCBX", 		refServicesCBX());
    	m.addAttribute("refStatusCBX", 			refStatusCBX());
    	m.addAttribute("refPersonTypeCBX", 		refPersonTypeCBX());
    	m.addAttribute("refLivePlaceCBX", 		refLivePlaceCBX());
    	m.addAttribute("refPropertyTypeCBX", 	refPropertyTypeCBX());
    	m.addAttribute("refBranchCBX", 			refBranchCBX());
    	m.addAttribute("secUserCBX", 			secUserCBX());
    	m.addAttribute("refBankCBX",		 	refBankCBX());
    	m.addAttribute("refCurrencyCBX",	 	refCurrencyCBX());
    	m.addAttribute("refAssCompanyCBX",	 	refAssCompanyCBX());
    	m.addAttribute("refObjectAssCBX",	 	refObjectAssCBX());
    	
     	return "contractsCardAsig";
    }
    
    @RequestMapping(value="/adaugaContract", method=RequestMethod.POST) 
    public String  adaugaContractPost( Model m , @ModelAttribute("contractItem") Contracts item,  
    			@RequestParam(value="pPostOperation", required=false) String pPostOperation) {
    	log.debug("AppController - adaugaContractPost - POST");
    	log.debug("AppController - adaugaContractaPost - pPostOperation = " +  pPostOperation );
    	Contracts contractItem = null;
//    	try {
        	item.setUpdatedByFk(secUserService.getCurrentUserId());
        	item.setUpdatedDate(new Date());
        	if (item.getResponsPersonal().getId()==-1) {
        		item.setResponsPersonal(null);
        	}
        	
        	if (item.getResponsPersonal2().getId()==-1) {
        		item.setResponsPersonal2(null);
        	}	
        	
        	if (item.getBlackListFlg()==null) {item.setBlackListFlg(0);}
//        	if (item.getContractatFlg()==null) {item.setContractatFlg(0);}
//        	if (item.getFinalizatFlg()==null) {item.setFinalizatFlg(0);}
//        	log.debug("personFlg="+item.getPersonFlg());
//        	log.debug("app="+item.getApplicationPersJur().getIdno());
        	if (item.getPersonFlg()==1) {
        		item.setApplicationPersJur(null);
	        	item.getApplicationPersFiz().setStatus(1);
	        	item.getApplicationPersFiz().setUpdatedByFk(secUserService.getCurrentUserId());
	        	item.getApplicationPersFiz().setUpdatedDate(new Date());
        	}
        	else{
        		item.setApplicationPersFiz(null);
        		item.getApplicationPersJur().setStatus(1);
            	item.getApplicationPersJur().setUpdatedByFk(secUserService.getCurrentUserId());
            	item.getApplicationPersJur().setUpdatedDate(new Date());
        	}
        	if (item.getRegCompanies().getId()==null) {item.setRegCompanies(null);}
        	if (item.getRegPersons().getId()==null) {item.setRegPersons(null);}
        	
        	if (pPostOperation.equalsIgnoreCase("send")){
        		if (item.getRefStatus().getId()==0) {
        		item.getRefStatus().setId(1);
        		}
        		else {
        			item.getRefStatus().setId(3);
        		}
        	}
//        	if (pPostOperation.equalsIgnoreCase("assign")){
//        		item.getRefStatus().setId(2);
//        	}
        	if (pPostOperation.equalsIgnoreCase("replayYes")){
        		item.getRefStatus().setId(item.getRefStatus().getId()+1);
        	}
        	if (pPostOperation.equalsIgnoreCase("replayNo")){
        		item.getRefStatus().setId(item.getRefStatus().getId()-1);
        	}
        	
        	//logic not for Financiar Bancar
        	if (pPostOperation.equalsIgnoreCase("remain")){
        		if (item.getRefDomains().getId()!=1 && item.getRefStatus().getId()==0) {
        		item.getRefStatus().setId(1);
        		}
        	}
        	
        	if (pPostOperation.equalsIgnoreCase("elab")){
        		item.getRefStatus().setId(2);
        	}
        	
        	if (pPostOperation.equalsIgnoreCase("print")){
        		item.getRefStatus().setId(4);
        	}
        	//-----------------------
        	
        	if (item.getConsultantComment().length()>0){
        		item.setChat(item.getChat()+"\n  ---  "+
        				secUserService.getProxyCurrentUser().getUserFullName()+" ["+
        				new SimpleDateFormat("dd.MM.yyyy HH:mm").format(new Date())+"] "+
        				item.getConsultantComment());
        		item.setConsultantComment(null);
        		item.setLastCommentUserFk(secUserService.getCurrentUserId());
        	}
        	if (item.getRefBank().getId()==-1) {
        		item.setRefBank(null);
        	}
        	
        	if ( item.getRefDomains().getId()!=1 && item.getContractDate()==null){//contractItem.getRefStatus().getId()==1 &&
				item.setContractDate(new Date());
        	}
  
        	//Operations with ClientFiles for RegPersons
        	if (item.getApplicationPersFiz()!=null){
        		RegPersons regPersonsItem = regPersonsService.get(item.getApplicationPersFiz().getRegPersons().getId(), secUserService.getProxyCurrentUser());
        		log.debug("----####---------------------------------");
        		log.debug("regpersonid="+regPersonsItem.getId());
        		log.debug("regpersonfiles="+regPersonsItem.getRegPersonsAss().size());
        		log.debug("----#####---------------------------------");
        		item.getApplicationPersFiz().getRegPersons().setUpdatedByFk(regPersonsItem.getUpdatedByFk());
        		item.getApplicationPersFiz().getRegPersons().setUpdatedDate(regPersonsItem.getUpdatedDate());
        		item.getApplicationPersFiz().getRegPersons().setRegCompanies(regPersonsItem.getRegCompanies());
        		//item.getApplicationPersFiz().getRegPersons().setOcupatia(regPersonsItem.getOcupatia());
        		item.getApplicationPersFiz().getRegPersons().setNotes(regPersonsItem.getNotes());
        		item.getApplicationPersFiz().getRegPersons().setRegPersonsAss(regPersonsItem.getRegPersonsAss());
        		
        		log.debug("----#####=== DB Size="+regPersonsItem.getClientFiles().size()+" App Size="+item.getApplicationPersFiz().getRegPersons().getClientFiles().size());
        		
        		if (regPersonsItem.getClientFiles().size()!= 0 && item.getApplicationPersFiz().getRegPersons().getClientFiles().size()==0) {
        			item.getApplicationPersFiz().getRegPersons().setClientFiles(regPersonsItem.getClientFiles());
        			log.debug("----#####DBnotnillAPPnull---------------------------------");
        		}
        		
        		List <ClientFiles> cList = item.getApplicationPersFiz().getRegPersons().getClientFiles();
        		List <ClientFiles> cListT = new ArrayList <ClientFiles>();
        		for (int i = 0; i < cList.size(); i++) {
        			//log.debug("------"+ cList.get(i).getId()+' '+ cList.get(i).getRefDomains().getId()+' '+ cList.get(i).getClass().toString());
        			if (cList.get(i).getRefDomains()!=null) {
	        			if (cList.get(i).getRefDomains().getId()!=null) {
	        				cListT.add(cList.get(i));
	        				//log.debug("---"+ cList.get(i).getId()+' '+ cList.get(i).getRefDomainsFk()+' '+ cList.get(i).getClass().toString());
	        			}
        			}	
        		}	    
        		item.getApplicationPersFiz().getRegPersons().setClientFiles(cListT);  

        	}
        	
        	//Operations with ClientFiles for RegCompanies
        	if (item.getApplicationPersJur()!=null){
        		RegCompanies regCompaniesItem = regCompaniesService.get(item.getApplicationPersJur().getRegCompanies().getId(), secUserService.getProxyCurrentUser());
        		log.debug("----####---------------------------------");
        		log.debug("regCompaniesid="+regCompaniesItem.getId());
        		log.debug("regCompaniesidfiles="+regCompaniesItem.getClientFiles().size());
        		log.debug("----#####---------------------------------");
        		item.getApplicationPersJur().getRegCompanies().setUpdatedByFk(regCompaniesItem.getUpdatedByFk());
        		item.getApplicationPersJur().getRegCompanies().setUpdatedDate(regCompaniesItem.getUpdatedDate());
        		item.getApplicationPersJur().getRegCompanies().setNotes(regCompaniesItem.getNotes());
        		if (regCompaniesItem.getRefBank()!=null) {
        			item.getApplicationPersJur().getRegCompanies().setRefBank(new RefBank());
        			item.getApplicationPersJur().getRegCompanies().getRefBank().setId((regCompaniesItem.getRefBank().getId()));
        		}
        		item.getApplicationPersJur().getRegCompanies().setBankCode(regCompaniesItem.getBankCode());
        		item.getApplicationPersJur().getRegCompanies().setBankAccount(regCompaniesItem.getBankAccount());
        		item.getApplicationPersJur().getRegCompanies().setRegCompaniesAss(regCompaniesItem.getRegCompaniesAss());
        		
        		log.debug("----#####=== DB Size="+regCompaniesItem.getClientFiles().size()+" App Size="+item.getApplicationPersJur().getRegCompanies().getClientFiles().size());
        		
        		if (regCompaniesItem.getClientFiles().size()!= 0 && item.getApplicationPersJur().getRegCompanies().getClientFiles().size()==0) {
        			item.getApplicationPersJur().getRegCompanies().setClientFiles(regCompaniesItem.getClientFiles());
        			log.debug("----#####DBnotnillAPPnull---------------------------------");
        		}
        		
        		List <ClientFiles> cList = item.getApplicationPersJur().getRegCompanies().getClientFiles();
        		List <ClientFiles> cListT = new ArrayList <ClientFiles>();
        		for (int i = 0; i < cList.size(); i++) {
        			//log.debug("------"+ cList.get(i).getId()+' '+ cList.get(i).getRefDomainsFk()+' '+ cList.get(i).getClass().toString());
        			if (cList.get(i).getRefDomains()!=null) {
	        			if (cList.get(i).getRefDomains().getId()!=null) {
	        				cListT.add(cList.get(i));
	        				//log.debug("---"+ cList.get(i).getId()+' '+ cList.get(i).getRefDomainsFk()+' '+ cList.get(i).getClass().toString());
	        			}
        			}
        		}	    
        		item.getApplicationPersJur().getRegCompanies().setClientFiles(cListT);  

        	}
        	
        	//log.debug("RegPersonFiles="+item.getApplicationPersFiz().getRegPersons().getClientFiles().size());
        	contractItem = contractsService.update(item, secUserService.getProxyCurrentUser());
        	log.debug("----****---------------------------------");
//		} 
//    	catch (Exception e) {
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	
      	if (pPostOperation.equalsIgnoreCase("remain")) {
    		m.addAttribute("contractItem", contractItem);	
    		
    		m.addAttribute("refCompanyCBX", 		refCompanyCBX());
    		m.addAttribute("refActivityTypeCBX", 	refActivityTypeCBX());
    		m.addAttribute("refDomainsCBX", 		refDomainsCBX());
    		m.addAttribute("refServicesCBX", 		refServicesCBX());
    		m.addAttribute("refStatusCBX", 			refStatusCBX());
    		m.addAttribute("refPersonTypeCBX", 		refPersonTypeCBX());
    		m.addAttribute("refLivePlaceCBX", 		refLivePlaceCBX());
    		m.addAttribute("refPropertyTypeCBX", 	refPropertyTypeCBX());
    		m.addAttribute("refBranchCBX", 			refBranchCBX());
    		m.addAttribute("secUserCBX", 			secUserCBX());
    		m.addAttribute("refBankCBX",		 	refBankCBX());
    		m.addAttribute("refCurrencyCBX",	 	refCurrencyCBX());
    		m.addAttribute("refAssCompanyCBX",	 	refAssCompanyCBX());
    		m.addAttribute("refObjectAssCBX",	 	refObjectAssCBX());
    		
    		m.addAttribute("errorMessage", "0");
    		
    		switch (item.getRefDomains().getId()) 
    		{ 
    		case 1: return "contractsCardFinBank";  
    		case 2: return "contractsCardMM"; 
    		case 3: return "contractsCardImob"; 
    		case 4: return "contractsCardAsig"; 
    		case 6: return "contractsCardEvCont";
    		default: return "contractsCardFinBank"; 
    		}
    		 
    	} 
      m.asMap().clear();
      if (contractItem.getRefStatus().getId()<=1) {
    	  return "redirect:/vizualizeazaAnchete";
      }
      else {
    	  return "redirect:/vizualizeazaContracte";
      }
    }   
    
    @RequestMapping(value="/adaugaAchitari", method=RequestMethod.GET) 
    public String  adaugaAchitariGet(Model m , @RequestParam(required=false) Integer pPersonalId, Integer pPartenerId) {
    	log.debug("AppController - adaugaAchitariGet - GET");
    	SecUser personalItem = null;
    	RegPartners partenerItem = null;
    	try {
    		if (pPersonalId != null) {
    			personalItem = secUserService.get(pPersonalId, secUserService.getProxyCurrentUser());
        	} 
    		
    		if (personalItem != null) {
    			m.addAttribute("personalItem", personalItem);
    		} else {
    			m.addAttribute("personalItem", secUserService.getNewUser());
    		}
    		
    		if (pPartenerId != null) {
    			partenerItem = regPartnersService.get(pPartenerId, secUserService.getProxyCurrentUser());
        	} 
        	
    		if (partenerItem != null) {
    			m.addAttribute("partenerItem", partenerItem);
    		} else {
    			m.addAttribute("partenerItem", new RegPartners());
    		}
        		
    		m.addAttribute("errorMessage", "0");
		} catch (Exception e) {
			m.addAttribute("personalItem", secUserService.getNewUser());
			m.addAttribute("partenerItem", new RegPartners());
			m.addAttribute("errorMessage", "Server Side Error Occured");
		}
    	
    	 m.addAttribute("refRegionsCBX", 	refRegionsCBX());
    	 m.addAttribute("refCityHallsCBX", 	refCityHallsCBX());
    	 m.addAttribute("refBranchCBX", 	refBranchCBX());
    	 m.addAttribute("refRoleCBX", 		refRoleCBX());
    	 
    	return "contractPaymentsCard";
    }
    
    /* ----------------------- Domenii SPECIFIC ------------------------------------ */
    
    @RequestMapping("/vizualizeazaDomenii")
    public String visualizeazaDomenii(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - visualizeazaDomenii");
        return "domeniiList";
    }      
    
    @RequestMapping("/vizualizeazaServicii")
    public String vizualizeazaServicii(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaServicii");
        return "serviciiList";
    }
    
    @RequestMapping("/vizualizeazaFiliale")
    public String vizualizeazaFiliale(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaFiliale");
        return "filialeList";
    }          
    
    @RequestMapping("/vizualizeazaTipuriActivitati")
    public String vizualizeazaTipuriActivitati(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaTipuriActivitati");
        return "tipuriActivitatiList";
    }
    
    @RequestMapping("/vizualizeazaTipuriProprietati")
    public String vizualizeazaTipuriProprietati(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaTipuriProprietati");
        return "tipuriProprietatiList";
    }
    
    
    @RequestMapping("/vizualizeazaBanci")
    public String vizualizeazaBanci(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaBanci");
        return "banciList";
    }
    
    @RequestMapping("/vizualizeazaFirme")
    public String vizualizeazaFirme(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - vizualizeazaFirme");
        return "firmeList";
    }
    
    @RequestMapping(value="/adaugaFirme", method=RequestMethod.GET) 
    public String  adaugaFirmeGet(Model m , @RequestParam(required=false) Integer pId) {
    	log.debug("AppController - adaugaFirmeGet - GET");
    	RefCompany companyItem = null;

//    	try {
    		if (pId != null) {
    			companyItem = refCompanyService.get(pId, secUserService.getProxyCurrentUser());
        	} 
    		else {
    			companyItem=new RefCompany();
//    			
//    			companiesItem.setRegCompaniesAss(regCompaniesAssList);
    		}
    		
    		if (companyItem != null) {
    			m.addAttribute("companyItem", companyItem);
    		} else {
    			m.addAttribute("companyItem", new RefCompany());
    		}
        		
    		m.addAttribute("errorMessage", "0");
    		
    		m.addAttribute("refBankCBX", 	refBankCBX());
//		} catch (Exception e) {
//			m.addAttribute("companiesItem", new RegCompanies());
//			m.addAttribute("errorMessage", "Server Side Error Occured");
//		}
    	return "firmeCard";
    }
    
	@RequestMapping(value = "/adaugaFirme", method = RequestMethod.POST)
	public String adaugaFirmePost(
			Model m,
			@ModelAttribute("companyItem") RefCompany item,
			@RequestParam(value = "pPostOperation", required = false) String pPostOperation) {
		
		log.debug("AppController - adaugaFirmePost - POST");
		log.debug("AppController - adaugaFirmePost - pPostOperation = "
				+ pPostOperation);
		RefCompany companyItem = null;
		
		//try {
			
			item.setUpdatedBy(secUserService.getCurrentUserId());
			item.setUpdatedDate(new Date());
			item.setStatus(1);
			companyItem = refCompanyService.update(item, secUserService.getProxyCurrentUser());
		//} catch (Exception e) {
		//	m.addAttribute("errorMessage", "Server Side Error Occured");
		//}

		if (pPostOperation.equalsIgnoreCase("remain")) {
			m.addAttribute("companyItem", companyItem);
			m.addAttribute("refBankCBX", 	refBankCBX());
	    	
			m.addAttribute("errorMessage", "0");
			return "firmeCard";
		}
		
		m.asMap().clear();
		return "redirect:/vizualizeazaFirme";
	}  
	
    
    
//    @RequestMapping("/personsList")
//    public String personsList(WebRequest request, Principal principal, Locale locale) {
//    	log.debug("AppController - personsList");
//        return "personsList";
//    }  
    
    

    
    
    
    
    
    
    
    
    
    
/* **********************************************************************************
 *		RAPOARTE
 * ********************************************************************************** */     
    @RequestMapping("/rapoarte")
    public String rapoarte(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - rapoarte");
    	return "rapoarte";
    }
    
/* **********************************************************************************
 *		FISIERE
 * ********************************************************************************** */    
    @RequestMapping("/fisiere")
    public String fisiere(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - fisiere");
        return "fisiere";
    }    
    
/* **********************************************************************************
 *		E-MAIL
 * ********************************************************************************** */
    @RequestMapping("/email")
    public String email(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - email");
        return "email";
    }
    
/* **********************************************************************************
 *		COMPANIE
 * ********************************************************************************** */    
    @RequestMapping("/companie")
    public String companie(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - companie");
        return "companie";
    }
    
/* **********************************************************************************
 *		UTILITATI
 * ********************************************************************************** */    
    @RequestMapping("/utilitati")
    public String utilitati(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - utilitati");
        return "utilitati";
    }    
  
    
/* **********************************************************************************
 *		CADOURI
 * ********************************************************************************** */    
    @RequestMapping("/cadouriSold")
    public String cadouriSold(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - cadouriSold");
    	
    	Integer currentUserRoleId = secUserService.getProxyCurrentUser().getUserRoleId(); 
    	if ( currentUserRoleId == 0 ||  currentUserRoleId ==1) {
    		return "cadouriAdminSold";	  
    	} else {
    		return "cadouriUserSold";
    	}
    }    

    @RequestMapping("/adaugaСadouri")
    public String adaugaСadouri(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - adaugaСadouri");
        return "adaugaСadouri";
    }        
    
    @RequestMapping("/documentsList")
    public String documentsList(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - documentsList");
    	
    	Integer currentUserRoleId = secUserService.getProxyCurrentUser().getUserRoleId(); 
    	if ( currentUserRoleId == 0 ||  currentUserRoleId ==1) {
    		return "documentsAdminList";	  
    	} else {
    		return "documentsUserList";
    	}
    }      
    
    
/* **********************************************************************************
 *		TEST
 * ********************************************************************************** */    
    @RequestMapping("/jsonTester")
    public String jsonTester(WebRequest request, Principal principal, Locale locale) {
    	log.debug("AppController - jsonTester");
        return "jsonTester";
    } 
    
}
